package game.worlds;

import echo.Body;
import hx.display.BitmapData;
import hx.display.Image;

/**
 * 地图块
 */
class MapDisplay extends Image implements IDisplay {
	/**
	 * 攻击的碰撞块预设，如果不存在`hitBody`，则意味着该对象无法被攻击
	 */
	public var hitBody(default, set):Body;

	private function set_hitBody(value:Body):Body {
		if (hitBody != null) {
			hitBody.entity = null;
			if (hitBody.world != null)
				hitBody.world.remove(hitBody);
		}
		this.hitBody = value;
		if (value != null) {
			value.entity = this;
			if (value.world == null && this.world != null) {
				this.world.echoWorld.add(value);
			}
		}
		return body;
	}

	/**
	 * 判断检测碰撞条件
	 * @param body 
	 * @return Bool
	 */
	public function condition(body:Body):Bool {
		return true;
	}

	/**
	 * 碰撞触发
	 * @param body 
	 */
	public function enter(body:Body):Void {}

	/**
	 * 物理碰撞器
	 */
	public var body(default, set):Body;

	private function set_body(value:Body):Body {
		if (body != null) {
			body.entity = null;
			body.on_move = null;
			if (body.world != null)
				body.world.remove(body);
		}
		this.body = value;
		if (value != null) {
			value.entity = this;
			value.on_move = this.setPoint;
			if (value.world == null && this.world != null) {
				this.world.echoWorld.add(value);
			}
		}
		return body;
	}

	public function setPoint(x:Float, y:Float):Void {
		super.x = x;
		super.y = y;
		if (this.hitBody != null) {
			this.hitBody.x = x;
			this.hitBody.y = y;
		}
	}

	override function set_x(value:Float):Float {
		if (this.body != null)
			this.body.x = value;
		else
			super.x = value;
		if (this.hitBody != null)
			this.hitBody.x = value;
		return value;
	}

	override function set_y(value:Float):Float {
		if (this.body != null)
			this.body.y = value;
		else
			super.y = value;
		if (this.hitBody != null)
			this.hitBody.y = value;
		return value;
	}

	public var world:World;

	override function set_data(value:BitmapData):BitmapData {
		this.originX = -value.width / 2;
		this.originY = -value.height;
		return super.set_data(value);
	}

	override function set_rotation(value:Float):Float {
		if (hitBody != null)
			hitBody.rotation = value;
		return super.set_rotation(value);
	}

	override function set_scaleX(value:Float):Float {
		if (hitBody != null)
			hitBody.scale_x = value;
		return super.set_scaleX(value);
	}

	override function set_scaleY(value:Float):Float {
		if (hitBody != null)
			hitBody.scale_y = value;
		return super.set_scaleY(value);
	}

	public function clean():Void {
		this.onClean();
	}

	public function onClean():Void {
		if (this.world != null) {
			this.world.removeMapDisplay(this);
		}
		this.body = null;
		this.hitBody = null;
		this.world = null;
	}
}
